//------------------------------------------------
// 说明: 该文件中函数主要用于保存几个主要操作所需的函数
//       如MidSearch, openLookUp, PostData等
//------------------------------------------------

//------------------------------------------------
function XmlHttpPost(webFile, sendXml) {    
    var retVal = $.ajax({
        url: webFile,
        type:'Post',
        data: sendXml,
        contentType: 'text/xml',
        async: false
    }).responseText;
    return retVal;
}

//------------------------------------------------
function XmlHttpGet(webFile) {

    var sendXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Toolkit></Toolkit>"
    
    var retVal = $.ajax({
        url: webFile,
        type: 'Get',
        data: sendXml,
        contentType: 'text/xml',
        async: false
    }).responseText;
    return retVal;
}
//------------------------------------------------


//================================================
//  Post data back to server
//================================================
var firstPost = true;
function PostData(tableName, fieldID, webFile, dataSet, save) {
    if (!firstPost) {
        var msg = "数据正在提交过程中，请稍后……";
        $.messager.alert('Error Message', msg, 'warning');
        return false;
    }
    firstPost = false;
    var sendXml = GenXMLData(tableName, fieldID, dataSet, save);

    Post2Server(webFile, sendXml, firstPost);
}

function Post2Server(url, data, firstPost) {
    $.ajax({
        url: url,
        type: 'Post',
        data: data,
        contentType: 'text/xml',
        beforeSend: function() {
            var wrap = $('#divMaskLayer');
            if (wrap.length > 0) {
                $('<div class="datagrid-mask"></div>').css({
                    display: 'block',
                    width: wrap.width(),
                    height: wrap.height(),
                    top: wrap.offset().top, // set the y axis
                    left: wrap.offset().left
                }).appendTo(wrap);
                $('<div class="datagrid-mask-msg"></div>')
				.html('Processing, please wait ...')
				.appendTo(wrap)
				.css({
				    display: 'block',
				    left: wrap.offset().left + (wrap.width() - $('.datagrid-mask-msg').outerWidth()) / 2,
				    top: wrap.offset().top + (wrap.height() - $('.datagrid-mask-msg').outerHeight()) / 2
				});
            }
        },
        success: function(responseText) {
            if (responseText.substring(0, 2) == "OK") {
                var idxBegin = responseText.indexOf(";Alert;");
                var idxEnd = responseText.lastIndexOf(";Alert;");
                var url;
                if (idxBegin < idxEnd && idxBegin > 0) {
                    alert(responseText.substring(idxBegin + 7, idxEnd));
                    url = responseText.substring(idxEnd + 7, responseText.length);
                }
                else
                    url = responseText.substring(2, responseText.length);
                firstPost = true;
                document.clear();
                document.location.href = url;
            }
            else {
                if ($('#listDataGrid').length > 0) {
                    $('#listDataGrid').html(responseText);
                }
                else {
                    $('.datagrid-mask').remove();
                    $('.datagrid-mask-msg').remove();

                    $.messager.alert('Error Message', responseText, 'error');
                }
            }

            firstPost = true;
        },
        error: function() {
            $('.datagrid-mask').remove();
            $('.datagrid-mask-msg').remove();
            firstPost = true;
        }
    })
}

function PostDataWithCallBack(tableName, fieldID, webFile, dataSet, save, onInit, onSuccess, onError) {
    if (!firstPost) {
        var msg = "数据正在提交过程中，请稍后……";
        $.messager.alert('Error Message', msg, 'warning');
        return false;
    }
    firstPost = false;
    var sendXml = GenXMLData(tableName, fieldID, dataSet, save);

    AJAXPost(webFile, sendXml, onInit, onSuccess, onError);
}

function AJAXPost(url, data, onInit, onSuccess, onError) {
    $.ajax({
        url: url,
        type: 'Post',
        data: data,
        contentType: 'text/xml',
        beforeSend: function() {
            if (onInit) {
                onInit();
            }
        },
        success: function(responseText) {
            if (onSuccess) {
                onSuccess(responseText);
            }
            firstPost = true;
        },
        error: function() {
            if (onError) {
                onError();
            }
            firstPost = true;
        }
    })
}

//================================================
//  Generate xml string from tree control
//================================================
function GenerateTreeData(tagTree, tableName, fieldID, dataSet, save) {
    var nodes = $(tagTree).tree('getChecked');

    $(tagTree).find('.tree-checkbox2').each(function() {
        var node = $(this).parent();
        nodes.push($.extend({}, $.data(node[0], 'tree-node'), {
            target: node[0],
            checked: node.find('.tree-checkbox').hasClass('tree-checkbox2')
        }));
    });

    var xml = "";
    
    var tableNameArr = tableName.split(",");
    var tableFieldArr = fieldID.split(";");

    var i = 0;
    for (i = 0; i < tableNameArr.length; i++) {
        var xmlRow = "";
        if (tableNameArr.length == tableFieldArr.length) {
            var columnName = tableFieldArr[i];
            var k = 0;
            for (k = 0; k < nodes.length; k++) {               
                var node = nodes[k];
                var id = node.id;
                var index = id.indexOf(columnName);
                if (index > -1) {
                    var length = columnName.length;
                    id = id.substring(index + length);
                    var item = "<" + columnName + ">" + id + "</" + columnName + ">";
                    xmlRow += "<" + tableNameArr[i] + ">" + item + "</" + tableNameArr[i] + ">";
                }                
            }            
        }
        
        xml = xml + xmlRow;
    }
    xml = xml + "<OtherInfo>";
    xml = xml + "<DataSet>" + ReplaceText(dataSet) + "</DataSet>" + "<Save>" + ReplaceText(save) + "</Save>";
    xml = xml + "</OtherInfo>";
    xml = "<Toolkit>" + xml + "</Toolkit>";
    return xml;
}

//================================================
//  Generate xml string
//================================================
function GenXMLData(tableName, fieldID, dataSet, save) {
    var tableNameArr = tableName.split(",");
    var tableFieldArr = fieldID.split(";");
    var fieldIDArr;
    var xml = "";
    var xmlRow = "";
    var rowCount;
    var eleObj;
    var i = 0;
    var j = 0;
    var k = 0;
    for (k = 0; k < tableNameArr.length; k++) {
        fieldIDArr = tableFieldArr[k].split(",");
        eleObj = document.all(fieldIDArr[0]);
        if (eleObj == null) {
            //alert("对象"+ fieldIDArr[i] +"不存在");
            rowCount = 1;
            //return false;
        } else {
            if (document.all(fieldIDArr[0], 0).tagName.toUpperCase() == "SELECT") {
                rowCount = eleObj.length;
                if (rowCount <= 1) {
                    rowCount = 1;
                } else if (document.all(fieldIDArr[0], rowCount - 1) == null) {
                    rowCount = 1;
                }
            } else {
                rowCount = document.all(fieldIDArr[0]).length;
                if (rowCount == null || rowCount == undefined)
                    rowCount = 1;
            }
        }
        for (i = 0; i < rowCount; i++) {
            xmlRow = "";
            for (j = 0; j < fieldIDArr.length; j++) {
                eleObj = document.all(fieldIDArr[j]);
                var xmlValue = "";
                if (eleObj == null) {
                    //alert("对象"+ fieldIDArr[j] +"不存在");
                } else {
                    eleObj = document.all(fieldIDArr[j], i);
                }
                if (eleObj == null) {
                    //alert("对象"+ fieldIDArr[j] + "."+ i +"不存在");
                }
                else {
                    if (eleObj.tagName.toUpperCase() == "INPUT") {
                        switch (eleObj.type.toUpperCase()) {
                            case "RADIO":
                                var raCount = document.all(fieldIDArr[j]).length;
                                if (raCount == undefined)
                                    raCount = 1;
                                for (var m = 0; m < raCount; m++) {
                                    eleObj = document.all(fieldIDArr[j], m);
                                    if (eleObj.checked) {
                                        xmlValue = eleObj.value;
                                        break;
                                    }
                                }
                                break;
                            case "CHECKBOX":
                                if (eleObj.checked)
                                    xmlValue = eleObj.value;
                                else
                                    xmlValue = "0";
                                break;
                            default:
                                xmlValue = eleObj.value;
                                break;
                        }
                    }
                    else {
                        xmlValue = eleObj.value;
                    }
                }
                xmlRow = xmlRow + "<" + fieldIDArr[j] + ">" + ReplaceText(xmlValue) + "</" + fieldIDArr[j] + ">";
            }
            xmlRow = "<" + tableNameArr[k] + ">" + xmlRow + "</" + tableNameArr[k] + ">";
            xml = xml + xmlRow;
        }
    }
    xml = xml + "<OtherInfo>";
    xml = xml + "<DataSet>" + ReplaceText(dataSet) + "</DataSet>" + "<Save>" + ReplaceText(save) + "</Save>";
    xml = xml + "</OtherInfo>";
    xml = "<Toolkit>" + xml + "</Toolkit>";
    return xml;
}

//================================================
//  弹出窗口搜索或选择类别相关函数
//================================================
var lastMouseX;
var lastMouseY;
var curPopupWindow;
var retLookUpObj;
var retLookUphdObj;
//------------------------------------------------
function setLastMousePosition(e) {
	if (navigator.appName.indexOf("Microsoft") != -1) e = window.event;
	lastMouseX = e.screenX;
	lastMouseY = e.screenY;
}
//------------------------------------------------
function openPopup(url, name, pWidth, pHeight, features, snapToLastMousePosition) {
	closePopup();
	if (snapToLastMousePosition) {
		if (lastMouseX - pWidth < 0) {
			lastMouseX = pWidth;
		}
		if (lastMouseY + pHeight > screen.height) {
			lastMouseY -= (lastMouseY + pHeight + 50) - screen.height;
		}
		lastMouseX -= pWidth;
		lastMouseY += 10;
		features +=	"screenX="+ lastMouseX +",left="+ lastMouseX +"screenY="+ lastMouseY +",top="+ lastMouseY;
	}
	curPopupWindow = window.open(url, name, features, false);
}
//------------------------------------------------
function closePopup() {
	if (curPopupWindow != null) {
		if (!curPopupWindow.closed) {
			curPopupWindow.close();
		}
		curPopupWindow = null;
	}
}
//------------------------------------------------
// 注: openLookup最多支持4个参数, 如openLookup(baseURL, retobjName, pos, brothName)
// retObjName: 指定返回时的对象名;  pos: 返回时对象的序号
function openLookup(baseURL) {
	var baseURL, retObjName, pos, brothName;
	if (openLookup.arguments.length > 1) {
		retObjName = openLookup.arguments[1];
		retLookUpObj = document.all(retObjName);
		retLookUphdObj = document.all("hd"+retObjName);
	}
	if (openLookup.arguments.length > 2) {
		pos = openLookup.arguments[2];
		retLookUpObj = document.all(retObjName, pos);
		retLookUphdObj = document.all("hd"+retObjName, pos);
	}
	if (openLookup.arguments.length > 3) {
		brothName = openLookup.arguments[3];
		var broth = document.all(brothName, pos);
		if (broth.item(broth.selectedIndex).value == "-1")
			return false;
	}
	openPopup(baseURL, "lookup", 300, 300, "width=250,height=200,toolbar=no,scrollbars=yes,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}

function openCodeTable(tableName, ctrlName) {
  openLookup("../Pages/WebInitPage.aspx?Source=CodeSelectPage&TableName=" + tableName, ctrlName)
}

//------------------------------------------------
function lookupPick(formName, parentIdElementName, parentEditElementName, id, display) {
	var parentIdElement = "document." + formName + "[\"" + parentIdElementName + "\"]";
	var parentEditElement = "document." + formName + "[\"" + parentEditElementName + "\"]";
	if (eval(parentIdElement + ".type") == "select-one") {
		var found = false;
		for (i = 0; i < eval(parentIdElement + ".options.length"); i++) {
			if (eval(parentIdElement + ".options[" + i + "].value") == id ) {
				eval(parentIdElement + ".selectedIndex=" + i);
				found = true;
				break;
			}
		}
		if (!found) {
			eval(parentIdElement + ".options[" + parentIdElement + ".options.length] = new Option('" + display + "','" + id + "')");
			eval(parentIdElement + ".selectedIndex=" + parentIdElement + ".options.length - 1");
		}
		eval(parentEditElement + ".value = " + "\"" + display +"\"");    
	} else {
		eval(parentIdElement + ".value = " + "\"" + id +"\"");    
		eval(parentEditElement + ".value = " + "\"" + display +"\"");    
	}
	closePopup();
	return false;
}

function lookupPick1(formName, parentIdElementName, parentEditElementName, retEleID, id, display) {
    var idElement = $('#' + parentIdElementName);
    var editElement = $('#' + parentEditElementName);
    if (idElement.attr("type") == "select-one") {    
		var found = false;
		for (i = 0; i < idElement.get(0).options.length; i++) {
		    if (idElement.get(0).options[i].value == id) {
		        idElement.get(0).selectedIndex = i;
				found = true;
				break;
			}
		}
		if (!found) {
			idElement.append("<option value='"+id+"'>"+display+"</option>");
			idElement.get(0).selectedIndex = idElement.get(0).selectedIndex.options.length - 1;
		}
		editElement.attr("value", display);   
	} else {
	    idElement.attr("value", id);
	    editElement.attr("value", display);  
	}
	closePopup();
	return false;
}
//------------------------------------------------


//================================================
//  浮动查询窗体函数
//================================================
var retMidSearchObj;
var retMidSearchhdObj;
var FloatDisplay = "floatDiv";
//------------------------------------------------
// 返回在浮动窗体中选中的值
// 给Hidden变量赋值
function returnItemValue(string, position, doc) {
	retMidSearchhdObj.value = doc.all("CODE_VALUE" + position).value;
	retMidSearchObj.blur();
	retMidSearchObj.value = string;
	retMidSearchObj.select();
	oldValue = "";
	closefloatDiv();
}
//------------------------------------------------
// 在浮动窗体中突出鼠标移动处的位置
function HoverCell(strOnOff, oSourceTag) {
	window.onerror = null;
	var isIE;
	var oTagID;
	if (navigator.appVersion.indexOf('MSIE') != -1)	{
		isIE = true;
		oTagID = oSourceTag.style;
	} else {
		isIE = false;
		oTagID = eval("ids." + oSourceTag.id);
	}
	if (strOnOff == 'on') {
		oTagID.backgroundColor = '#003366';
		oTagID.color = '#FFFFFF';
	} else {
		oTagID.backgroundColor = '';
		oTagID.color = '';
	}
	return true;
}
//------------------------------------------------
// 隐藏浮动窗体
function closefloatDiv() {
	var floatDivObj = document.all(FloatDisplay).style;
	floatDivObj.left = -500;
	floatDivObj.top  = -500;
	floatDivObj.visibility = "hidden";
	showElement("SELECT");
}
//------------------------------------------------
// 鼠标在浮动窗体外点击时，隐藏浮动窗体
var floatdivflag = 1;
function DocOnClick() {
	if(floatdivflag == 1) {
		var floatDivObj = document.all(FloatDisplay)
		if(floatDivObj != null) {
			if(floatDivObj.style == undefined) return;
			if (floatDivObj.style.visibility == "visible")		{
				floatDivObj.style.left = -500;
				floatDivObj.style.top  = -500;
				floatDivObj.style.visibility = "hidden";
				showElement("SELECT");
			}
		}
	}
	else
		floatdivflag = 1;
}
//------------------------------------------------
// 显示浮动窗体并确定好位置
function openfloatDiv() {
	var floatDivObj = document.all(FloatDisplay).style;
	var objLeft   = retMidSearchObj.offsetLeft;
	var objTop    = retMidSearchObj.offsetTop + retMidSearchObj.offsetHeight + 2;
	var objParent = retMidSearchObj.offsetParent;
	while (objParent.tagName.toUpperCase() != "BODY")	{
		objLeft  += objParent.offsetLeft;
		objTop   += objParent.offsetTop;
		objParent = objParent.offsetParent;
	}
	floatDivObj.left = objLeft;
	var scroll = 0;

	floatDivObj.top  = objTop - scroll;
	floatDivObj.visibility = "visible";
	hideSelectElement(objTop, objLeft);
}
//------------------------------------------------
// 隐藏页面中被遮盖的Select对象
function hideSelectElement(objTop, objLeft){
	var selobj, selobjLeft, selobjTop, selobjParent;	
	var floatDivObj = document.all(FloatDisplay).style;
	for (i=0; i<document.all.tags("SELECT").length; i++)	{
		selobj = document.all.tags("SELECT")[i];
		if (!selobj || !selobj.offsetParent)
			continue;
		// Find the element's offsetTop and offsetLeft relative to the BODY tag.
		selobjLeft   = selobj.offsetLeft;
		selobjTop    = selobj.offsetTop;
		selobjParent = selobj.offsetParent;
		while (selobjParent.tagName.toUpperCase() != "BODY")	{
			selobjLeft  += selobjParent.offsetLeft;
			selobjTop   += selobjParent.offsetTop;
			selobjParent = selobjParent.offsetParent;
		}
		// Adjust the element's offsetTop relative to the dropdown menu
		if (objLeft > (selobjLeft + selobj.offsetWidth))
			;
		else if(selobjLeft > (objLeft + parseInt(floatDivObj.width)))
			;
		else if (selobjTop > (parseInt(floatDivObj.height) + objTop))
			;
		else if (objTop > (selobjTop + selobj.offsetHeight))
			;
		else
			selobj.style.visibility = "hidden";
	}
}
//------------------------------------------------
// 显示页面中被隐藏的Select对象
function showElement(elmID){
	for (i=0; i<document.all.tags(elmID).length; i++)	{
		obj = document.all.tags(elmID)[i];
		if (!obj || !obj.offsetParent)
			continue;
		obj.style.visibility = "";
	}
}
//------------------------------------------------

var oldValue = "";
function internalFastSearch1(floatDivObj, type, value, myHidden) {
	var pos, brothName;
    var mid_length;
    var srcElement = window.event.srcElement;
    var condition = (floatDivObj.innerHTML != "" && document.all("MidSearchTable", 0) != null && document.all("MidSearchTd") != null);
    if (srcElement.type != "text" && condition) {
    }
    else
		retMidSearchObj = srcElement;
	retMidSearchhdObj = myHidden;
	var key_code = window.event.keyCode;
	if (condition) {
	  	mid_length = document.all("MidSearchTable", 0).rows.length;
		if(key_code == 38) {
 	        if(MidSearchCurrentRow == -1) {
 				MidSearchCurrentRow = mid_length -1;
 				floatDiv.scrollTop = floatDiv.scrollHeight;
 			}
 			else {
 				HoverCell("off", document.all("MidSearchTd", MidSearchCurrentRow));

		     	MidSearchCurrentRow --; 
		   		if(MidSearchCurrentRow == -1) {
		     		MidSearchCurrentRow = mid_length -1;
		     		floatDiv.scrollTop = floatDiv.scrollHeight;
		     	}
		    }
		     	
		    HoverCell("on", document.all("MidSearchTd", MidSearchCurrentRow));
		    if(floatDiv.scrollTop > (MidSearchCurrentRow * 21 - 50)) {
				floatDiv.scrollTop -= 21;
       		}
		    return true;
		}
		if (key_code == 40)	{
 	        if(MidSearchCurrentRow == -1)
 				MidSearchCurrentRow = 0;
 			else {
 				HoverCell("off", document.all("MidSearchTd", MidSearchCurrentRow));

		     	MidSearchCurrentRow ++; 
		   		if(MidSearchCurrentRow == mid_length) {
			     	floatDiv.scrollTop = 0;
			     	MidSearchCurrentRow = 0;
			    }
		    }
		     	
		    HoverCell("on", document.all("MidSearchTd", MidSearchCurrentRow));

  		    if((MidSearchCurrentRow * 21 - 70)> floatDiv.scrollTop) {
				floatDiv.scrollTop += 21;
       		}
			return true;
		}
		if(key_code == 13 && MidSearchCurrentRow > -1 && (floatDivObj.style.visibility == "visible")) {
			returnItemValue(document.all("CODE_NAME" + (MidSearchCurrentRow+1), 0).value, MidSearchCurrentRow+1, document);
			return true;
		}
	}
    if (value == "")
		myHidden.value = "";
	return false;
}

function internalFastSearch2(floatDivObj, type, value, myHidden, xml2, divflag) {
	var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Toolkit><SELECT><TYPE>"+ type +"</TYPE><VALUE>"+ ReplaceText(value) +"</VALUE></SELECT>" + xml2 + "</Toolkit>";
	floatDivObj.innerHTML = XmlHttpPost("../Pages/WebEasySearch2Page.zjx?Source=" + type, xml);
	if (floatDivObj.innerHTML != "") {
  		MidSearchCurrentRow = -1;
		floatdivflag = divflag;
		openfloatDiv();
	}
}

function internalFastSearch3(baseCount, args, retMidSearchObj) {
	var argCount = args.length;// FastSearch.arguments.length;

	var xml2 = "";
	if (argCount > baseCount) {
		var count = argCount - baseCount;
		var pos = GetRowID(retMidSearchObj);
		for (i = 0; i < count / 2; ++i) {
			var index = baseCount + i * 2;
			var obj = document.all(args[index + 1], pos);
			var objValue = (obj == null) ? "" : ReplaceText(obj.value);
			xml2 += "<REF><Field>" + args[index] + "</Field><RefValue>" + objValue + "</RefValue></REF>";
		}
	}	
	return xml2;
}

function FastSearch(type, value, myHidden) {
	var floatDivObj = document.all("floatDiv");

	if (internalFastSearch1(floatDivObj, type, value, myHidden))
		return;
	
    if (oldValue == value)
		return false;
	oldValue = value;

	var args = FastSearch.arguments;
	var xml2 = internalFastSearch3(3, args, retMidSearchObj);
	internalFastSearch2(floatDivObj, type, value, myHidden, xml2, 1);	
}

function FastSearch2(type, value, myHidden) {
	var floatDivObj = document.all("floatDiv");
	
	if (internalFastSearch1(floatDivObj, type, value, myHidden))
		return;

	if (myHidden.value != "" && oldValue != value)
	   return false; 

  /*if (oldValue == value)
		return false;*/
	oldValue = value;

	var args = FastSearch2.arguments;
	var xml2 = internalFastSearch3(3, args, retMidSearchObj);
	internalFastSearch2(floatDivObj, type, value, myHidden, xml2, 0);	
}

function ListFastSearch(type, value, myHidden) {
	var floatDivObj = document.all("floatDiv");

	if (internalFastSearch1(floatDivObj, type, value, myHidden))
		return;
	
    if (oldValue == value)
		return false;
	oldValue = value;

	var args = ListFastSearch.arguments;
	var xml2 = internalFastSearch3(3, args, retMidSearchObj);
	internalFastSearch2(floatDivObj, type, value, myHidden, xml2, 1);	
}

function ListFastSearch2(type, value, myHidden) {
	var floatDivObj = document.all("floatDiv");

	if (internalFastSearch1(floatDivObj, type, value, myHidden))
		return;

	if (myHidden.value != "" && oldValue != value)
	   return false; 

  /*if (oldValue == value)
		return false;*/
	oldValue = value;

	var args = ListFastSearch2.arguments;
	var xml2 = internalFastSearch3(3, args, retMidSearchObj);
	internalFastSearch2(floatDivObj, type, value, myHidden, xml2, 0);	
}

function GetQueryXml(conditionValue, xslFile, dataSetName) {
    return "<?xml version=\"1.0\" encoding=\"utf-8\"?><Toolkit><OtherInfo><Condition>" + conditionValue + "</Condition><XslFile>" + xslFile + "</XslFile><DataSet>" + dataSetName + "</DataSet></OtherInfo></Toolkit>";
}

function GetCustChild(conditionValue, childID, xslFile, webFile, dataSetName) {
	var childString = XmlHttpPost(webFile, GetQueryXml(conditionValue, xslFile, dataSetName));
	if (childString != "")
	{
		var childObj = document.all(childID, 0);
		childObj.outerHTML = childString;
	}
}
function GetOtherInfo(conditionValue, childID, webFile, dataSetName) {
	var i = 0;
	var j = 0;
	var nodeLength = 0;
	var otherObj;
	var childIDArr = childID.split(",");
	var otherInfoStr = XmlHttpPost(webFile, GetQueryXml(conditionValue, "", dataSetName));
	var xmlObj = GetXmlDocument();
	xmlObj.loadXML(otherInfoStr);
	var nodeLen = xmlObj.documentElement.childNodes.length;
	if (nodeLen == 0)
		for(j = 0; j < childIDArr.length; j++)
			document.all(childIDArr[j], 0).value = "";
	else
	{
		var searchNode = xmlObj.documentElement.childNodes.item(0);
		nodeLength = searchNode.childNodes.length;
	
		for (i = 0; i < nodeLength; i++)
			for(j = 0; j < childIDArr.length; j++)
				if (searchNode.childNodes.item(i).nodeName == childIDArr[j])
				{
					document.all(childIDArr[j], 0).value = searchNode.childNodes.item(i).text;
					break;
				}
	}
}

function ReplaceText(strValue) {
	var str = strValue;
	str = str.replace(/&/g, "&amp;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	return str;
}

function ChangeObjectType(thisElementObj) {
    var rowID = GetRowID(thisElementObj);
    var selectIndex = thisElementObj.selectedIndex;
    var  newobject =  document.all("Sibling" + thisElementObj.name, rowID);    
    document.all(newobject.value, rowID).value = "";
	document.all("hd" + newobject.value, rowID).value = "";
    document.all("hd" + newobject.value + "Type", rowID).value = thisElementObj.item(selectIndex).value;
}
function TogDisplay(n) {
	var oButton = document.all("Button_"+n,0);
	var oItems = document.all("Expand_"+n,0);
	if ((oItems.style.display == "") || (oItems.style.display == "block")) 
	{
		oItems.style.display = "none";
		oButton.src = "../Images/plus.gif";
	} 
	else 
	{
		oItems.style.display = "block";
		oButton.src = "../Images/minus.gif";
		oButton.onClick = "TogDisplay(" + n + ")";
	}
	return false;
}
function GetChildSX(conditionValue, childID, xslFile, webFile, dataSetName) {
	var ohdExpand = document.all("hdExpand_"+conditionValue, 0);
	if (ohdExpand.value != "true")
	{
		GetCustChild(conditionValue, childID, xslFile, webFile, dataSetName);
		ohdExpand.value = "true";
	}
	TogDisplay(conditionValue);
}

function gotonextfocus() {
	var tmp = 0;
	if(window.event.keyCode==13) {
		var eleObj = window.event.srcElement;
		var eleAry = frmData.elements;
		var eCount = eleAry.length;
		for(i=0; i<eCount; i++) {
			if (eleObj == eleAry[i])
				tmp = i;
		}
		window.event.returnValue = false;
		if (tmp == eCount-1)
			return false;
		while (eleAry[tmp+1].tagName.toUpperCase()=="INPUT" && eleAry[tmp+1].type.toUpperCase()=="HIDDEN") {
			tmp++;
			if (tmp == eCount-1)
				return false;
		}
		while (eleAry[tmp+1].disabled) {
			tmp++;
			if (tmp == eCount-1)
				return false;
		}
		window.setTimeout("frmData.elements["+(tmp+1)+"].focus()", 100);
	}
}

function GetRowID(eleobj) {
	var objTr = eleobj.offsetParent.parentElement;
	var objTb = eleobj.offsetParent;
	while (objTb.tagName.toUpperCase() != "TABLE")	{
		objTb = objTb.offsetParent;
	}
	var trCount = objTb.rows.length;
	//jinzhao
	//to be verified
	if ($(objTr).find("input[name='dtRowID']").length == 0)
	    return 0;
	//to be verified
	var dtCount = $(objTb).find("input[name='dtRowID']").length;

	return dtCount - 1;
}

//================================================
//  特殊处理
//================================================
function openLookup1(baseURL) {
	var tmp = 0;
	var thisElementObj = window.event.srcElement;
	//	var eleCount = document.images(thisElementObj.name).length;
	//jinzhao
	//ImgUSER_ORIGIN
	var eleCount = $('#'+ thisElementObj.name).length;
	if (eleCount == undefined)
		eleCount = 1;

	//点击图片不弹出窗口
	if(thisElementObj.enable != undefined && thisElementObj.enable == false)
		return ;

	for (i=0; i<eleCount; i++) {
		if (thisElementObj == document.images(thisElementObj.name, i)) {
			tmp = i;
			break;
		}
}
    baseURL = baseURL + "&retEleID=" + tmp;
	//	baseURL = baseURL + "&SearchType=" + document.frmData.elements("hd"+thisElementObj.name.substring(3)+"Type", tmp).value;
	var elementName = "hd" + thisElementObj.name.substring(3) + "Type";
	baseURL = baseURL + "&SearchType=" + $('#' + elementName).val();
	//http://localhost:53316/Web/Pages/WebDialogSearch2Page.zjx?IdElementName=hdUSER_ORIGIN&EditElementName=USER_ORIGIN&retEleID=0&SearchType=SX
	
	//alert(baseURL);
	var argCount = openLookup1.arguments.length;
	var xml2 = "";
	if (argCount > 1) {
		var count = argCount - 1;
		var pos = GetRowID(thisElementObj);
		for (i = 0; i < count / 2; ++i) {
			var index = 1 + i * 2;
			var obj = document.all(openLookup1.arguments[index + 1], pos);
			var objValue = (obj == null) ? "" : ReplaceText(obj.value);
			xml2 += "<REF><Field>" + openLookup1.arguments[index] + "</Field><RefValue>" + objValue + "</RefValue></REF>";
		}
		baseURL += "&RefValue=" + xml2;
	}	
	openPopup(baseURL, "lookup", 400, 400, "width=250,height=200,toolbar=no,scrollbars=yes,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}
function openLookup2(brothName, thisObj, baseURL, typeName) 
{
	var rowID = GetRowID(thisObj);
	var broth = document.all(brothName, rowID);
	if (broth.item(broth.selectedIndex).value == "-1")
		return false;
	openLookup1(baseURL, typeName);
}
function FastSearch1(brothName, thisObj, type, value, myHidden)
{     
	var rowID = GetRowID(thisObj);
	var broth = document.all(brothName, rowID);
	if (broth.item(broth.selectedIndex).value == "-1")
	{
		thisObj.value = "";
		return false;
	}
	FastSearch(type, value, myHidden);
}

function Expand(TableName,imgName)
{  
    if (document.all(TableName).style.display=="none")
    {
        document.all(TableName).style.display="";
        document.images(imgName).src="../images/collapse_detail.gif";
    }
    else
    {
        document.all(TableName).style.display="none";
        document.images(imgName).src="../images/expand_detail.gif";
    }
    return;
}

//参数n=0时为隐藏页面上所有按钮，n=1则隐藏第一个按钮
function disableButtonById(n) {
// var spaDivs = document.body.all.tags("SPAN");
// var btnDivs = new Array();
// var i = 0;
// var j = 0;
// for(i=0; i<spaDivs.length; i++) {
//  if (spaDivs[i].className == "clsButtonFace") {
//   btnDivs[j] = spaDivs[i];
//   j++;
//  }
// }
// if (n==0) {
//  for (i=0; i<j; i++) {
//   btnDivs[i].className = "clsButtonDisabled";
//   btnDivs[i].oldHtml = btnDivs[i].innerHTML;
//   btnDivs[i].innerHTML = btnDivs[i].innerText;
//  }
// } else {
//  btnDivs[n-1].className = "clsButtonDisabled";
//  btnDivs[n-1].oldHtml = btnDivs[n-1].innerHTML;
//  btnDivs[n-1].innerHTML = btnDivs[n-1].innerText;
// }
}

function enableButtonById(n) {
 var spaDivs = document.body.all.tags("SPAN");
 var btnDivs = new Array();
 var i = 0;
 var j = 0;
 for(i=0; i<spaDivs.length; i++) {
  if (spaDivs[i].className == "clsButtonDisabled") {
   btnDivs[j] = spaDivs[i];
   j++;
  }
 }
 if (n==0) {
  for (i=0; i<j; i++) {
   btnDivs[i].className = "clsButtonFace";
   btnDivs[i].innerHTML = btnDivs[i].oldHtml;
   btnDivs[i].oldHtml = "";
  }
 } else {
  btnDivs[n-1].className = "clsButtonDisabled";
  btnDivs[n-1].innerHTML = btnDivs[n-1].oldHtml;
  btnDivs[n-1].oldHtml = "";
 }
}

//--------------------------------------
// validate the value
function Validate(action) {
    var valid = true;
    //check input controls
    $('input').each(function() {
        var clsObj = $(this).attr('class');
        if (clsObj) {
            var index = clsObj.indexOf("validatebox-invalid");
            if (index > -1) {
                var inputCtrl = $(this);
                $.messager.alert('Error Message', 'Please check the error information', 'error', function() {
                    inputCtrl.focus();
                });
                return valid = false;
            }
        }
    });
    if (valid) {
        //check select controls
        $('select').each(function() {

        });
    }

    if (valid) {
        Post(action);
    }
}
//--------------------------------------

//--------------------------------------
function PostFunc(url, source, save)
{
   var guid = frmData._GUID.value;
   if (save =="Save")
      Post2(url, guid, save);
  else if (save == "SaveNew") {
   //jz
      //url += "&RetURL=../Pages/WebInsertPage.aspx%3fSource=" + source;
      Post2(url, guid, save);
   }
}
//--------------------------------------
var MidSearchCurrentRow = -1;

function MouseHoverCell(strOnOff, oSourceTag) 
{
 	 var mid_length = document.all("MidSearchTable", 0).rows.length;
	 if(MidSearchCurrentRow >=0 && MidSearchCurrentRow < mid_length)
	 {
	 	HoverCell("off", document.all("MidSearchTd", MidSearchCurrentRow));
	 }

	 for(i = 0; i< mid_length; i++)
	 if(oSourceTag == document.all("MidSearchTd", i))
	 {
	   	MidSearchCurrentRow = i;
	   	break;	
	 }
	  	    
	HoverCell("on", oSourceTag);
	return true;
}

function GetRelatedInfos(querys, values, queryFields, resultFields, curRowID, resolverRegName)
{
  var valueArr = values.split(",");
  var queryArr = querys.split(",");
  if (valueArr.length != queryArr.length) {
	alert("参数有误，querys和values个数必须相同！");
	return false;
  }
  var xml = "<Info><QueryFields>" + queryFields + "</QueryFields><ResultFields>" + resultFields + "</ResultFields><RegName>"
    + resolverRegName + "</RegName></Info><Condition>";
  for (i = 0; i < valueArr.length; ++i) 
    xml += "<" + queryArr[i] + ">" + document.all(valueArr[i], curRowID).value + "</" + queryArr[i] + ">";
 	var argCount = GetRelatedInfos.arguments.length;
 	if (argCount > 6) {
 	  var count = argCount - 6;
 	  for (i = 0; i < count / 2; ++i) {
 	    var index = 6 + i * 2;
 	    var tag = GetRelatedInfos.arguments[index];
 	    xml += "<" + tag + ">" + GetRelatedInfos.arguments[index + 1] + "</" + tag + ">"
 	  }
 	}
  xml += "</Condition>";
  xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Toolkit>" + xml + "</Toolkit>";

  var result = XmlHttpPost("../Pages/WebPostOperationPage.zjx?Source=TKQueryValue", xml);
  if (result != "") {
    var xmlDoc = GetXmlDocument();
    xmlDoc.loadXML(result);
    xmlDoc.setProperty("SelectionLanguage", "XPath");
    if (xmlDoc.documentElement == null) return;
    
    var resultArr = resultFields.split(",");
    for (i = 0; i < resultArr.length; ++i) {
      var node = xmlDoc.documentElement.selectSingleNode("//" + resultArr[i]);
      document.all(resultArr[i],curRowID).value = node.text;
    }
  }
}

function Export2Excel(rowsCount, url)
{
	if (rowsCount > 10000) {
		alert("记录数太多，不要超过10000条！");
		return false;
	}
	document.location.href = url;		
}

function CheckRows(rowsCount)
{
	if (rowsCount > 10000) {
		alert("记录数太多，不要超过10000条！");
		return false;
	}
	else
		return true;
}

function DivOnMouseOver(obj) {
	if(obj.innerText != "" && obj.innerText != "-")
	{
		//var cs = obj.currentStyle.cursor;
		//obj.className = "DivOver";
	    //obj.style.cursor = cs;
	    $(obj).css("cursor", "hand");
	    $(obj).addClass("tree-node-hover");
	}
}
function DivOnMouseOut(obj) {
    //obj.className = "DivOut";
    $(obj).removeClass("tree-node-hover");
}


function CheckUpload()
{
	try
	{
		if (uploadPop != null && uploadPop.CurrentUploadStatus == 1)
		{
			alert("请等待文件上传结束！");
			return false;
		}
		return true;
	}
	catch(e)
	{
		return true;
	}
}

function OpenUploadPage(typeRuleObj, maxSizeObj, fileObj, pathObj, sizeObj, mimeTypeObj, onUploadedEvent)
{
	if (!CheckUpload())
		return;
	var uploadObj = window.event.srcElement.offsetParent;
	var uploadPopStyle = document.all("uploadPop").style;
	var objLeft   = uploadObj.offsetLeft;
	var objTop    = uploadObj.offsetTop + uploadObj.offsetHeight + 2;
	var objParent = uploadObj.offsetParent;
	while (objParent.tagName.toUpperCase() != "BODY")	{
		objLeft  += objParent.offsetLeft;
		objTop   += objParent.offsetTop;
		objParent = objParent.offsetParent;
	}
	uploadPopStyle.left = objLeft;
	var scroll = 0;
	
	uploadPopStyle.top  = objTop - scroll;
	uploadPopStyle.visibility = "hidden";

	uploadPop.InitUpload(typeRuleObj, maxSizeObj, fileObj, pathObj, sizeObj, mimeTypeObj, onUploadedEvent);
}

function ViewUpload(file)
{
	var floatDivObj = document.all("floatDiv");
	var srcElement = window.event.srcElement;
    	var condition = (floatDivObj.innerHTML != "" && document.all("MidSearchTable", 0) != null && document.all("MidSearchTd") != null);
    	if (srcElement.type != "img" && condition) {
    	}
    	else
		retMidSearchObj = srcElement;
	floatDivObj.innerHTML = "<table width='100%' border='0' cellspacing='0' cellpadding='2' align='center'>" + 
		"<tr><td><img src='" + file + "'/></td></tr></table>";
	floatdivflag = 1;
	openfloatDiv();
}